package com.cd.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBUtil {
	private Connection connection = null;
	private Statement statement = null;
	private ResultSet resultSet = null;

	/**
	 * 得到数据库连接,用于后续使用prestatement
	 * 
	 * @return
	 */
	public Connection getConnection() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/user", "root", "root");
			// statement = connection.createStatement();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return this.connection;
	}

	/**
	 * 得到statement
	 * 
	 * @return
	 * @throws SQLException
	 */
	public Statement getStatement() throws SQLException {
		connection = getConnection();
		return connection.createStatement();
	}

	/**
	 * 输入sql语句进行查询
	 * 
	 * @param sql
	 * @return
	 * @throws SQLException
	 */
	public ResultSet query(String sql) throws SQLException {
		connection = getConnection();
		return connection.createStatement().executeQuery(sql);
	}
	
	public int update(String sql) throws SQLException{
		connection = getConnection();
		return connection.createStatement().executeUpdate(sql);
	}
	

	/**
	 * 关闭连接
	 */
	public void closeService() {
		try {
			if (connection != null) {
				if (connection.isClosed() == false) {
					connection.close();
				}
			}
			if (statement != null) {
				if (statement.isClosed() == false) {
					statement.close();
				}
			}
			if (resultSet != null) {
				if (resultSet.isClosed() == false) {
					resultSet.close();
				}
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
